package cn.edu.scnu.semart.user.controller;

import cn.edu.scnu.semart.common.result.Result;
import cn.edu.scnu.semart.common.utils.UserContext;
import cn.edu.scnu.semart.model.user.Address;
import cn.edu.scnu.semart.user.service.AddressService;
import cn.edu.scnu.semart.vo.user.AddressAddDTO;
import cn.edu.scnu.semart.vo.user.AddressUpdateDTO;
import cn.edu.scnu.semart.vo.user.SingleNumVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;

    /** 当前用户查询自己的地址列表 */
    @GetMapping("/my")
    public Result<List<Address>> myAddresses(HttpServletRequest request) {
        Integer userId = UserContext.getUserId(request);
        return Result.ok(addressService.listByUser(userId));
    }

    /** 新增地址 */
    @PostMapping("/add")
    public Result<Void> add(@RequestBody AddressAddDTO dto,
                            HttpServletRequest request) {
        Integer userId = UserContext.getUserId(request);
        addressService.addAddress(dto,userId);
        return Result.ok(null);
    }

//    /** 修改地址（只能改自己的） */
//    @PutMapping("/{id}")
//    public Result<Void> update(@PathVariable Integer id,
//                               @RequestBody Address address,
//                               @RequestAttribute("currentUserId") Integer userId) {
//        address.setAddressId(id);
//        address.setUserId(userId);
//        addressService.updateById(address);
//        return Result.ok(null);
//    }
    @PutMapping("/update")
    public Result<Void> update(@Valid @RequestBody AddressUpdateDTO dto,
                               HttpServletRequest request) {
        Integer userId = UserContext.getUserId(request);
        addressService.updateAddress(dto, userId);
        return Result.ok(null);
    }

    /** 删除地址（只能删自己的） */
    @DeleteMapping("/delete/{addressId}")
    public Result<Void> delete(@PathVariable Integer addressId,
                               HttpServletRequest request) {
        Integer userId = UserContext.getUserId(request);
        addressService.lambdaUpdate()
                .eq(Address::getAddressId, addressId)
                .eq(Address::getUserId, userId)
                .remove();
        return Result.ok(null);
    }

    /** 设为默认地址 */
    @PostMapping("/setDefault")
    public Result<Void> setDefault(@Valid @RequestBody SingleNumVo body,
                                   HttpServletRequest request) {
        Integer id = body.getId();
        Integer userId = UserContext.getUserId(request);
        addressService.setDefault(id, userId);
        return Result.ok(null);
    }

    /**
     * 供【订单】等其他微服务调用
     * 根据 addressId 查询地址完整信息
     * 不做用户归属校验，因为调用方已经是内部服务
     */
    @GetMapping("/internal/{addressId}")
    public Result<Address> getAddressForOrder(@PathVariable Integer addressId) {
        Address address = addressService.getById(addressId);
        if (address == null) {
            // 返回 404 语义，调用方自己处理
            return Result.fail(null);
        }
        return Result.ok(address);
    }


    /**
     * 查询所有地址（内部服务调用）
     */
    @GetMapping("/internal/all")
    public List<Address> getAllAddresses() {
        return addressService.list();
    }


    // 根据用户ID和地址ID获取地址（路径变量）
    @GetMapping("/{userId}/address/{addressId}")
    public Address getAddressById(
            @PathVariable("userId") Integer userId,
            @PathVariable("addressId") Integer addressId) {
        return addressService.getAddressById(userId, addressId);
    }
    // 根据地址ID列表批量查询地址（查询参数）
    @GetMapping("/address/listByIds")
    public List<Address> getAddressesByIds(
            @RequestParam("addressIds") List<Integer> addressIds) {
        return addressService.getAddressesByIds(addressIds);
    }
}